var express = require('express')
var fs = require('fs')
var path = require('path')

var app = express()
app.use(express.static('static'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

//注册接口
app.post('/user/register', (req, res) => {
    var { phone,password,password} = req.body

    var filepath = path.join(__dirname, './json/user.json')
    var arr = fs.readFileSync(filepath);
    arr = arr.toString() ? JSON.parse(arr) : []

    var i = arr.findIndex((item,index) => {
        return item.phone == phone
    })
    if (i != -1) {
        res.send({ code: 400, message: '该手机号已经被使用' })
    } else {
        arr.push({ ...req.body })
        fs.writeFileSync(filepath, JSON.stringify(arr), 'utf-8');
        res.send({ code: 200, message: '注册成功！' })
    }
})

//登录接口
app.post('/user/login', (req, res) => {
    var { phone, password } = req.body

    var filepath = path.join(__dirname, './json/user.json')
    var arr = fs.readFileSync(filepath);
    arr = arr.toString() ? JSON.parse(arr) : []

    var i = arr.findIndex((item,index) => {
        return item.phone == phone && item.password == password
    })
    if (i != -1) {
        res.send({ code: 200, message: '登陆连接成功！', userinformation: arr[i]})
    } else {
        res.send({ code: 400, message: '登陆连接失败！' })
    }
})


app.listen(6060, () => {
    console.log('服务端在运行');
})